﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;

namespace Circus.Utility {

    /// <summary>
    /// 提供网络相关辅助函数。
    /// </summary>
    public static class NetHelper {

        /// <summary>
        /// 向服务器提交数据并返回数据。
        /// </summary>
        /// <param name="url">请求的地址。</param>
        /// <param name="data">请求的数据。</param>
        /// <param name="method">请求的谓词。</param>
        /// <param name="contentType">请求的文档类型。</param>
        /// <param name="timeout">请求的超时毫秒数。</param>
        /// <returns>返回服务器响应的内容。</returns>
        public static string request(string url, string data = null, string method = "POST", string contentType = "text/json", int timeout = 60000) {

            if (data != null && method.Equals("GET", StringComparison.OrdinalIgnoreCase)) {
                if (url.IndexOf('?') >= 0) {
                    url += "&";
                } else {
                    url += "?";
                }
                url += data;
            }

            var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
            httpWebRequest.ContentType = contentType;
            httpWebRequest.Method = method;
            if (timeout > 0) {
                httpWebRequest.Timeout = timeout;
            }

            if (data != null && method.Equals("POST", StringComparison.OrdinalIgnoreCase)) {
                using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream())) {
                    streamWriter.Write(data);
                }
            }

            using (var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse()) {
                using (var streamReader = new StreamReader(httpResponse.GetResponseStream())) {
                    return streamReader.ReadToEnd();
                }
            }

        }

    }
}
